import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shenling_flutter/utils/auth.dart';
import 'package:shenling_flutter/utils/dio.dart';

class Pickup extends StatefulWidget {
  const Pickup({super.key});

  @override
  State<Pickup> createState() => _PickupState();
}

class _PickupState extends State<Pickup> {
  //定义刷新组件控制器
  final RefreshController _refreshController = RefreshController();
  List pickList = [];
  //接口参数
  Map<String, dynamic> params = {
    'endTime': '',
    'page': 1,
    'pageSize': 10,
    'status': 1,
    'startTime': '',
    'transportTaskId': ''
  };
  //加载动画
  bool _isLoading = true;
  //获取任务列表数据
  @override
  void initState() {
    super.initState();
    // 确保Auth实例已经初始化
    Future.delayed(Duration.zero, () async {
      await Auth().init();
      if (Auth().getToken() != null) {
        getPickList();
      }
    });
  }

  getPickList() async {
    setState(() {
      _isLoading = true;
    });
    final res = await http.request('get', '/driver/tasks/list', null, params);
    print(res);
    setState(() {
      pickList = res['data']['items'];
      //获取当前页码
      params['page'] = res['data']['page'];
      _isLoading = false;
    });
  }

  //下拉刷新
  _onRefresh() async {
    setState(() {
      //1.页码重置为第一页
      params['page'] = 1;
      //2.清空数据
      pickList.clear();
    });
    //3.重新请求数据
    await getPickList();
    //4.完成刷新
    _refreshController.refreshCompleted();
    //5.重置加载状态->允许再次上拉加载
    _refreshController.resetNoData();
  }

//上拉加载
  _onLoading() async {
    final res =
        await await http.request('get', '/driver/tasks/list', null, params);
    // 总页数->统一转换为数字类型
    final int totalPage = int.parse(res['data']['pages'].toString());
    //当前页码小于总页数
    if (params['page'] < totalPage) {
      setState(() {
        params['page'] += 1;
        pickList.addAll(res['data']['items']);
      });
      //数据加载完成
      _refreshController.loadComplete();
    } else {
      //无数据提示
      _refreshController.loadNoData();
    }
  }

  @override
  void dispose() {
    // 释放控制器资源
    _refreshController.dispose();
    super.dispose();
  }

//状态标签处理
  Widget _buildStatusTag(int status) {
    List statusTag = [
      {
        'status': '待提货',
        'color': Colors.red,
        'bgColor': const Color.fromARGB(255, 255, 195, 190),
      },
      {
        'status': '在途',
        'color': const Color.fromARGB(255, 224, 217, 250),
        'bgColor': const Color.fromARGB(255, 188, 174, 248),
      },
      {
        'status': '改派',
        'color': const Color.fromARGB(255, 108, 109, 108),
        'bgColor': const Color.fromARGB(255, 192, 255, 190),
      },
      {},
      {
        'status': '已作废',
        'color': const Color.fromARGB(255, 133, 132, 132),
        'bgColor': const Color.fromARGB(255, 180, 180, 180),
      },
      {
        'status': '已完成',
        'color': const Color.fromARGB(255, 199, 224, 248),
        'bgColor': const Color.fromARGB(255, 142, 194, 243),
      },
    ];
    return Container(
        decoration: BoxDecoration(
          color: statusTag[status]['bgColor'],
          borderRadius: BorderRadius.circular(4),
        ),
        child: Container(
          width: 60,
          padding: const EdgeInsets.all(3),
          child: Text(
            statusTag[status]['status'],
            style: TextStyle(color: statusTag[status]['color']),
            textAlign: TextAlign.center,
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return _isLoading && Auth().getToken() != null
        ? const Center(
            child: CircularProgressIndicator(),
          )
        : Container(
            padding: const EdgeInsets.all(10),
            child: pickList.isEmpty
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset('assets/imgs/ic_not_found.png'),
                      const Text('空空如也哦~')
                    ],
                  )
                //刷新组件
                : SmartRefresher(
                    controller: _refreshController,
                    //启用下拉刷新
                    enablePullDown: true,
                    //启用上拉加载
                    enablePullUp: true,
                    //下拉刷新回调
                    onRefresh: _onRefresh,
                    //下拉头部样式
                    header: const WaterDropHeader(),
                    //上拉加载回调
                    onLoading: _onLoading,
                    //上拉头部样式
                    footer: const ClassicFooter(
                      loadingText: "正在加载中...",
                      canLoadingText: "释放加载更多",
                      noDataText: "没有更多数据了",
                    ),
                    child: ListView.builder(
                      itemCount: pickList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Container(
                          padding: const EdgeInsets.all(10),
                          margin: const EdgeInsets.only(top: 10, bottom: 10),
                          width: MediaQuery.sizeOf(context).width,
                          color: Colors.white,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              //顶部编号
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                      '任务编号: ${pickList[index]['startAgencyId']}'),
                                  _buildStatusTag(pickList[index]['status'] - 1)
                                ],
                              ),
                              const SizedBox(
                                height: 10,
                              ),
                              //地点起始
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    padding: const EdgeInsets.all(6),
                                    decoration: const BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Colors.black,
                                    ),
                                    child: const Center(
                                        child: Text(
                                      '起',
                                      style: TextStyle(color: Colors.white),
                                    )),
                                  ),
                                  const SizedBox(
                                    width: 10,
                                  ),
                                  //地址
                                  Expanded(
                                      child: Text(
                                    pickList[index]['startAddress'],
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ))
                                ],
                              ),
                              //分割线
                              Container(
                                margin: const EdgeInsets.only(left: 10),
                                height: 20,
                                child: const VerticalDivider(
                                  width: 1,
                                  color: Colors.grey,
                                ),
                              ),
                              //地点终止
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    padding: const EdgeInsets.all(6),
                                    decoration: const BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Colors.red,
                                    ),
                                    child: const Center(
                                        child: Text(
                                      '止',
                                      style: TextStyle(color: Colors.white),
                                    )),
                                  ),
                                  const SizedBox(
                                    width: 10,
                                  ),
                                  //地址
                                  Expanded(
                                      child: Text(
                                    pickList[index]['endAddress'],
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  )),
                                ],
                              ),
                              const SizedBox(
                                height: 10,
                              ),
                              // 分割线
                              const Divider(
                                height: 1,
                                color: Colors.grey,
                              ),
                              //提货时间
                              const SizedBox(
                                height: 10,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      const Text('提货时间：'),
                                      Text(
                                          pickList[index]['planDepartureTime']),
                                    ],
                                  ),
                                  ElevatedButton(
                                      onPressed: () {},
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: const Color.fromARGB(
                                            255, 249, 100, 50), // 背景色
                                        foregroundColor: Colors.white, // 文字颜色
                                      ),
                                      child: const Text('提货'))
                                ],
                              )
                            ],
                          ),
                        );
                      },
                    )));
  }
}
